import UserEntityClass from '@/utils/entitys/UserEntity.class'
import FeedbackClass from '@/utils/entitys/Feedback.class'
import moment from "moment";
import {getAppLocalPath, getLengthId} from "@/utils/common";
import {decodeFile, ecodeFile} from "@/utils/CodingsUtils";
import {encrypt} from "adm-zip/methods/zipcrypto";
import Minizip from "minizip-asm.js";
const path = require('path')
const fs = require('fs')
const compressing = require('compressing')
let { remote } = require('electron')
import iconv, { decode } from 'iconv-lite';
import {encodeGbk} from "@/utils/fileUtils";
import {conver2} from "@/utils/Code2Code";
const password='lanjian@chrtc'
const archiver = require('archiver');
archiver.registerFormat('zip-encrypted', require("archiver-zip-encrypted"));
import * as zip from '@zip.js/zip.js';

// uuid
function generateUUID () {
  let d = new Date().getTime()
  if (window.performance && typeof window.performance.now === 'function') {
    // use high-precision timer if available
    d += performance.now()
  }
  let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
  return uuid
}
function getRandomId() {
  return Math.floor((Math.random() * 100000000) + 1)
}
function clearFileCon(file) {
  fs.writeFileSync(file, '{}')
}
function clearFileConList(file) {
  fs.writeFileSync(file, '[]'.trim())
}
/**
 * 获取当前时间戳(毫秒)
 */
function getNowMilliSecond() {
  return Math.floor(Date.now())
}
function deepGetFile(dir, filename) {
  let backList = []
  let list = fs.readdirSync(dir)

  for (let index in list) {
    let item = path.resolve(dir, list[index])
    if (fs.statSync(item).isDirectory()) {
      backList = backList.concat(deepGetFile(item, filename))
    } else {
      if (item.includes(filename)) {
        backList.push(item)
      }
    }
  }
  return backList
}
function deepGetDirectory(dir, filename) {
  let backList = []
  let list = fs.readdirSync(dir)
  for (let index in list) {
    let item = path.resolve(dir, list[index])
    console.log(item)
    if (fs.statSync(item).isDirectory()) {
      if(item.indexOf(filename)> -1){
        backList.push(item)
        console.log('file--'+item)
        return backList
      }
      backList = backList.concat(deepGetDirectory(item, filename))
    }
  }
  return backList
}
function getcurDate() {
  let currentDate = new Date()
  let year = currentDate.getFullYear().toString()
  let month = (currentDate.getMonth() + 1).toString()
  if (month.length === 1) {
    month = '0' + month
  }
  let date = currentDate.getDate().toString()
  if (date.length === 1) {
    date = '0' + date
  }
  let hour = currentDate.getHours().toString()
  if (hour.length === 1) {
    hour = '0' + hour
  }
  let minute = currentDate.getMinutes().toString()
  if (minute.length === 1) {
    minute = '0' + minute
  }
  let second = currentDate.getSeconds().toString()
  if (second.length === 1) {
    second = '0' + second
  }
  return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
}
// 获取用户
function getUser () {
  const user = fs.readFileSync(getAppLocalPath()+'dbson/User.dbson', 'utf-8')
  return JSON.parse(user)
}
// 查询用户,没有新增
export const getPassWord = (psd) => {
  return new Promise((resolve, reject) => {
    console.log("sx--",getSystemDir())
    fs.readFile(getAppLocalPath()+'dbson/User.dbson', 'utf-8', function(err, dataStr) {
      if (err) {
        return console.log('读取文件失败2' + err.message)
      }
      console.log('读取文件成功2' + dataStr)
      if (dataStr.trim().length === 0) {
        // 如果第一次登录，需要初始化密码
        const user = new UserEntityClass()
        user.setId(generateUUID())
        user.setPassWord(psd.password)
        user.setUploadTime(getcurDate())
        // 写入文件
        fs.writeFile(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(user), function(err) {
          if (err) {
            return console.log('文件写入失败3' + err.message)
          }
          console.log('文件写入成3')
        })
        // eslint-disable-next-line no-empty
      } else {
        const user = JSON.parse(dataStr)
        resolve(user)
      }
    })
  })
}
function setFileId(fileid, companyId) {
  fs.readFile(getAppLocalPath()+'dbson/User.dbson', 'utf-8', function(err, dataStr) {
    if (err) {
      return console.log('读取文件失败2' + err.message)
    }
    // 如果第一次登录，需要初始化密码
    const user = JSON.parse(dataStr)
    user.fileid = fileid
    user.companyId = companyId
    // 写入文件
    fs.writeFile(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(user), function(err) {
      if (err) {
        return console.log('文件写入失败3' + err.message)
      }
      console.log('文件写入成3')
    })
  })
}
// 修改密码
export const editPassWord = (product) => {
  return new Promise((resolve, reject) => {
    const option = {
      flag: 'w'
    }
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/User.dbson', 'utf-8', function(err, dataStr) {
      const user = JSON.parse(dataStr)
      user.password = product.password
      user.uploadtime = getcurDate()
      const updateuser = JSON.stringify(user, null, 2)
      fs.writeFile(getAppLocalPath()+'dbson/User.dbson', updateuser, option, function(err) {
        if (err) {
          resolve(0)
          return
        }
        resolve(1)
      })
    })
  })
}
// 查询反馈意见
export const getFeedback = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/Feedback.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr==""?"[]":dataStr)
      console.log("bbc--",list)
      console.log("1212--",getJLID())
      let lsarr = list.filter(function(value){
        console.log("2222---",value.jlid)
        //筛选条件
        return value.jlid==getJLID()
      })
      console.log("4141---",lsarr)
      resolve(lsarr || [])
    })
  })
}
// 查询整改会议 => 研究整改工作
export const getRectificationMeeting = () => {
  return new Promise((resolve, reject) => {
    if(getJLID()==""){
      resolve([])
    }
    console.log("ls--",getJLID())
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationMeeting.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      const last_list = list.filter(function (value) {
        console.log("ls2--",value.jlid)
        return value.jlid==getJLID()
      })
      console.log("ls3--",last_list)
      resolve(last_list || [])
    })
  })
}
// 新增/修改整改会议 => 研究整改工作
export const addRectificationMeeting = (product) => {
  console.log(product)
  return new Promise((resolve, reject) => {
    if(getJLID()==""){
      resolve(0)
      return
    }
    let userinfo = getUser()
    // 保存版本信息
    userinfo.yjvs = getRandomId()
    fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo), )
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationMeeting.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.
      parse(dataStr)
      console.log(product)
      const selStr=fs.readFileSync(getAppLocalPath()+'dbson/lanjianJLSelected.dbson', 'utf-8')
      if(selStr==""){
        resolve(0)
      }
      // 读取记录,判断是否存在
      if (product.id !== undefined) {
        // 存在更新
        for (let i = 0; i < list.length; i++) {
          if (product.id === list[i].id) {
            // eslint-disable-next-line no-unused-expressions
            // eslint-disable-next-line no-unused-expressions
            product.startMeetingTime = product.meetingTime ? product.meetingTime[0] : ''
            // eslint-disable-next-line no-unused-expressions
            product.endMeetingTime = product.meetingTime ? product.meetingTime[1] : ''
            product.meetingType = parseInt(product.meetingType)
            product.jlid=getJLID()
            list[i] = product
            // const updatemeet = JSON.stringify(list, null, 2)
            fs.writeFile(getAppLocalPath()+'dbson/RectificationMeeting.dbson', JSON.stringify(list), function (err) {
              if (err) {
                resolve(0)
                return
              }
              resolve(1)
            })
          }
        }
      } else {
        // 不存在新增
        const list = JSON.parse(dataStr)
        product.id = generateUUID()
        // eslint-disable-next-line no-unused-expressions
        product.startMeetingTime = product.meetingTime ? product.meetingTime[0] : ''
        // eslint-disable-next-line no-unused-expressions
        product.endMeetingTime = product.meetingTime ? product.meetingTime[1] : ''
        product.meetingType = parseInt(product.meetingType)
        product.jlid=getJLID()
        product.uploadTime=getcurDate()
        list.push(product)
        fs.writeFile(getAppLocalPath()+'dbson/RectificationMeeting.dbson', JSON.stringify(list), function (err) {
          if (err) {
            resolve(0)
            return
          }
          resolve(1)
        })
      }
    })
  })
}
// 删除整改会议 => 研究整改工作
export const delRectificationMeeting = (product) => {
  console.log("pid--",product)
  return new Promise((resolve, reject) => {
    let userinfo = getUser()
    // 保存版本信息
    userinfo.yjvs = getRandomId()
    fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationMeeting.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr==""?"[]":dataStr)
      // eslint-disable-next-line no-empty
      for (let i = 0; i < list.length; i++) {
        // eslint-disable-next-line no-empty
        if (list[i].id === product.id) {
          list.splice(i, 1)
        }
      }
      fs.writeFile(getAppLocalPath()+'dbson/RectificationMeeting.dbson', JSON.stringify(list), function(err) {
        if (err) {
          resolve(0)
          return
        }
        resolve(1)
      })
    })
  })
}
// 查询整改方案详情
export const getRectificationPlan = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationPlan.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || {})
    })
  })
}
// 查询整改方案列表
export const getRectificationPlanList = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationPlanList.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })
  })
}
// 查询整改方案审批记录
export const getRectificationPlanSpjl = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationPlanList.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })
  })
}
// 新增/修改整改方案详情
export const addRectificationPlan = (product) => {
  return new Promise((resolve, reject) => {
    const planObj={
      jlid:"",
      planTotal:{}
    }
    let plans_list=[]
    const plans=fs.readFileSync(getAppLocalPath()+'dbson/RectificationPlanAllinfos.dbson',"utf-8")
    const jl_dbson=fs.readFileSync(getAppLocalPath()+'dbson/lanjianJLSelected.dbson',"utf-8")
    product.uploadTime = getcurDate()
    planObj.planTotal=product
    if(getJLID()==""){
      resolve(0)
    }
    planObj.jlid=getJLID()
    if(plans==""){
      planObj.id=getNowMilliSecond()
      plans_list.push(planObj)
    }else{
      plans_list=JSON.parse(plans)
      let lsarr = plans_list.filter(function(value){
        //筛选条件
        return value.jlid==getJLID()
      })
      if(lsarr==undefined||lsarr.length==0){
        planObj.id=getNowMilliSecond()
        planObj.version=getNowMilliSecond()
        plans_list.push(planObj)
      }else{
        planObj.id=lsarr[0].id===undefined?getNowMilliSecond()+"":lsarr[0].id
        planObj.version=getNowMilliSecond()
        planObj.f_status=lsarr[0].f_status===undefined?"1":lsarr[0].f_status
        const index = plans_list.indexOf(lsarr)
        const newFileList = plans_list.slice()
        newFileList.splice(index, 1)
        plans_list = newFileList
        plans_list.push(planObj)
      }
    }
    fs.writeFile(getAppLocalPath()+'dbson/RectificationPlanAllinfos.dbson', JSON.stringify(plans_list), function (err) {
      if (err) {
        resolve(0)
        return
      }
      resolve(1)
    })
  })
}
// 新增/修改整改报告详情
export const addRectificationReportTotal = (product) => {
  return new Promise((resolve, reject) => {
    const planObj={
      jlid:"",
      planTotal:{}
    }
    product.version=getNowMilliSecond()
    planObj.f_status=product.f_status
    let plans_list=[]
    const plans=fs.readFileSync(getAppLocalPath()+'dbson/RectificationReportAllinfos.dbson',"utf-8")
    product.uploadTime = getcurDate()
    if(product.id==undefined||product.id==""){
      product.id=getNowMilliSecond()
    }
    planObj.planTotal=product
    if(getJLID()==""){
      resolve(0)
    }
    planObj.jlid=getJLID()
    if(plans==""){
      plans_list.push(planObj)
    }else{
      plans_list=JSON.parse(plans)
      let lsarr = plans_list.filter(function(value){
        //筛选条件
        return value.jlid==getJLID()
      })
      if(lsarr==undefined||lsarr.length==0){
        planObj.id=getNowMilliSecond()
        plans_list.push(planObj)
      }else{
        planObj.id=lsarr[0].id
        const index = plans_list.indexOf(lsarr)
        const newFileList = plans_list.slice()
        newFileList.splice(index, 1)
        plans_list = newFileList
        plans_list.push(planObj)
      }
    }
    fs.writeFile(getAppLocalPath()+'dbson/RectificationReportAllinfos.dbson', JSON.stringify(plans_list), function (err) {
      if (err) {
        resolve(0)
        return
      }
      resolve(1)
    })
  })
}
// 新增/修改整改报告详情
export const addRectificationZGGKTotal = (product) => {
  return new Promise((resolve, reject) => {
    const planObj={
      jlid:"",
      planTotal:{}
    }
    let plans_list=[]
    const plans=fs.readFileSync(getAppLocalPath()+'dbson/RectificationZGGKAllinfos.dbson',"utf-8")
    product.uploadTime = getcurDate()
    product.version=getNowMilliSecond()
    planObj.planTotal=product
    if(getJLID()==""){
      resolve(0)
    }
    planObj.jlid=getJLID()
    if(plans==""){
      planObj.id=getNowMilliSecond()

      plans_list.push(planObj)
    }else{
      plans_list=JSON.parse(plans)
      let lsarr = plans_list.filter(function(value){
        //筛选条件
        return value.jlid==getJLID()
      })
      if(lsarr==undefined||lsarr.length==0){

        planObj.id=getNowMilliSecond()
        plans_list.push(planObj)
        console.log("gg1--",planObj)
      }else{
        console.log("gg--",lsarr)
        planObj.f_status=lsarr[0].f_status==undefined?undefined:lsarr[0].f_status
        planObj.id=lsarr[0].id
        const index = plans_list.indexOf(lsarr)
        const newFileList = plans_list.slice()
        newFileList.splice(index, 1)
        plans_list = newFileList
        plans_list.push(planObj)
      }
    }
    fs.writeFile(getAppLocalPath()+'dbson/RectificationZGGKAllinfos.dbson', JSON.stringify(plans_list), function (err) {
      if (err) {
        resolve(0)
        return
      }
      resolve(1)
    })
  })
}
//获取整改方案总体概况
export const getRectificationPlanTotal = (product) => {
  return new Promise((resolve, reject) => {
    const plan=fs.readFileSync(getAppLocalPath()+'dbson/RectificationPlanAllinfos.dbson',"utf-8")
    if(getJLID()==""){
      resolve(JSON.parse("{}"))
    }
    if(plan==""){
      resolve(JSON.parse("{}"))
    }
    let lsarr = (JSON.parse(plan)).filter(function(value){
      //筛选条件
      return value.jlid==getJLID()
    })
    console.log("s1--",lsarr)
    if(lsarr==undefined||lsarr.length==0){
      resolve(JSON.parse("{}"))
    }
    console.log("sd--",lsarr[0])
    //lsarr[0].planTotal.f_status= lsarr[0].f_status
    resolve(lsarr[0].planTotal===undefined?{}:lsarr[0].planTotal)
  })
}
//获取整改报告总体概况
export const getRectificationReportTotal = (product) => {
  return new Promise((resolve, reject) => {
    const plan=fs.readFileSync(getAppLocalPath()+'dbson/RectificationReportAllinfos.dbson',"utf-8")
    if(getJLID()==""){
      resolve(JSON.parse("{}"))
    }
    if(plan==""){
      resolve(JSON.parse("{}"))
    }
    let lsarr = (JSON.parse(plan)).filter(function(value){
      //筛选条件
      return value.jlid==getJLID()
    })
    console.log("s1--",lsarr)
    if(lsarr==undefined||lsarr.length==0){
      resolve(JSON.parse("{}"))
    }
    console.log("sd--",lsarr[0])
    lsarr[0].planTotal.f_status=lsarr[0].f_status
    resolve(lsarr[0].planTotal)
  })
}

export const getRectificationZGGKTotal = (product) => {
  return new Promise((resolve, reject) => {
    const plan=fs.readFileSync(getAppLocalPath()+'dbson/RectificationZGGKAllinfos.dbson',"utf-8")
    if(getJLID()==""){
      resolve(JSON.parse("{}"))
    }
    if(plan==""){
      resolve(JSON.parse("{}"))
    }
    let lsarr = (JSON.parse(plan)).filter(function(value){
      //筛选条件
      return value.jlid==getJLID()
    })
    console.log("s1--",lsarr)
    if(lsarr==undefined||lsarr.length==0){
      resolve(JSON.parse("{}"))
    }
    console.log("sd--",lsarr[0])
    resolve(lsarr[0].planTotal)
  })
}
//修改整改方案单条
export const editRectificationPlanSignle = (product,type) => {
  return new Promise((resolve, reject) => {
    const plans=JSON.parse(fs.readFileSync(getAppLocalPath()+'dbson/Feedback.dbson',"utf-8"))
    // let lsarr = (JSON.parse(plan)).filter(function(value){
    //   //筛选条件
    //   return value.id==product.id
    // })
    // lsarr[0]=product
    //
    // for(var i=0;i<plans.length;i++){
    //
    // }
    //
    plans.forEach(item=>{
      console.log("1--",item.id+":"+product.id)
      if(item.id == product.id){
        item.zgfa_measure=product.zgfa_measure
        item.zgfa_time= product.zgfa_time
        item.zgfa_department=product.zgfa_department
        item.zgfa_leader=product.zgfa_leader
        item.zgfa_persion=product.zgfa_persion
        item.zgfa_zgtype=product.zgfa_zgtype
        item.zgfa_endtime=product.zgfa_endtime==""?"":moment(product.zgfa_endtime).format('YYYY-MM-DD')
        item.zgtz_zrr=product.zgtz_zrr
        item.zgtz_whss=product.zgtz_whss
        item.zgtz_wszd=product.zgtz_wszd
        item.zgtz_complete_info=product.zgtz_complete_info
        item.plan_status=product.plan_status?product.plan_status:0
        item.zgtz_marks=product.zgtz_marks
        if(type===1){
          let plan_list=JSON.parse(fs.readFileSync(getAppLocalPath()+"dbson/RectificationPlanAllinfos.dbson","utf-8")==""?"[]":fs.readFileSync(getAppLocalPath()+"dbson/RectificationPlanAllinfos.dbson","utf-8"))

          if(plan_list.length==0){
            const  plobj={
              jlid:getJLID(),
              version:getNowMilliSecond()
            }
            plan_list.push(plobj)
          }else {

            for (let i = 0; i < plan_list.length; i++) {
              if (plan_list[i].jlid === getJLID()) {
                plan_list[i].version = getNowMilliSecond()
                console.log("ls---",plan_list)
              }
            }
          }

          fs.writeFileSync(getAppLocalPath()+"dbson/RectificationPlanAllinfos.dbson",JSON.stringify(plan_list))
        }
        if(type===2){
          let tz_list=JSON.parse(fs.readFileSync(getAppLocalPath()+"dbson/Rectification.dbson","utf-8")==""?"[]":fs.readFileSync(getAppLocalPath()+"dbson/Rectification.dbson","utf-8"))

          if(tz_list.length==0){
            const  tzobj={
              jlid:getJLID(),
              version:getNowMilliSecond()
            }
            tz_list.push(tzobj)
          }else {
            for (let i = 0; i < tz_list.length; i++) {
              if (tz_list[i].jlid === getJLID()) {
                tz_list[i].version = getNowMilliSecond()
              }
            }
          }
          fs.writeFileSync(getAppLocalPath()+"dbson/Rectification.dbson",JSON.stringify(tz_list))
        }
      }
    })

    fs.writeFileSync(getAppLocalPath()+'dbson/Feedback.dbson',JSON.stringify(plans))
    resolve(1)
  })
}
export const getJLID=()=>{
  const jl_dbson=fs.readFileSync(getAppLocalPath()+'dbson/lanjianJLSelected.dbson',"utf-8")
  if(jl_dbson==""){
    return ""
  }
  return JSON.parse(jl_dbson)[0].sessionId+""+JSON.parse(jl_dbson)[0].roundId+""+JSON.parse(jl_dbson)[0].unitId
}
// 新增/修改整改方案列表
export const addRectificationPlanList = (product) => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationPlanList.dbson', 'utf-8', function(err, dataStr) {
      const option = {
        flag: 'w'
      }
      const list = JSON.parse(dataStr)
      // 读取记录,判断是否存在
      if (dataStr.indexOf(product.id)) {
        // 存在更新
        for (let i = 0; i < list.length; i++) {
          if (product.id === list[i].id) {
            product.uploadTime = getcurDate()
            const updatelist = JSON.stringify(product, null, 2)
            fs.writeFile(getAppLocalPath()+'dbson/RectificationPlanList.dbson', updatelist, option, function (err) {
              if (err) {
                resolve(0)
                return
              }
              resolve(1)
            })
          }
        }
      } else {
        // 不存在新增
        const list = JSON.parse(dataStr)
        product.uploadTime = getcurDate()
        list.push(product)
        fs.writeFile(getAppLocalPath()+'dbson/RectificationPlanList.dbson', JSON.stringify(list), function (err) {
          if (err) {
            resolve(0)
            return
          }
          resolve(1)
        })
      }
    })
  })
}
// 查询整改报告
export const getRectificationReport = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationReport.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || {})
    })
    // let db = conn()
    // db.all('select * from RectificationReport', (err, rows) => {
    //   if (err) reject(err)
    //   resolve(rows || [])
    // })
  })
}
// 查询整改报告列表
export const getRectificationReportList = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationReportList.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })
    // let db = conn()
    // db.all('select * from RectificationReportList', (err, rows) => {
    //   if (err) reject(err)
    //   resolve(rows || [])
    // })
  })
}
// 查询整改报告审批历史
export const getRectificationReportSpjl = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationReportSpjl.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })
  })
}
// 新增台账
export const addRectificationLegder = (product) => {
  return new Promise((resolve, reject) => {
    let userinfo = getUser()
    // 保存版本信息
    userinfo.tzvs = getRandomId()
    fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
    // eslint-disable-next-line node/handle-callback-err
    product.uploadTime = getcurDate()
    fs.writeFile(getAppLocalPath()+'dbson/RectificationLedger.dbson', JSON.stringify(product), function (err) {
      if (err) {
        resolve(0)
        return
      }
      resolve(1)
    })
  })
}
// 台账查询
export const getRectificationLegder = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationLegder.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || {})
    })
  })
}

// 截止时间查询
export const getRectifTimes = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/ZGDate.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list)
    })
  })
}

// 新增整改公开
export const addRectification = (product) => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    let userinfo = getUser()
    // 保存版本信息
    userinfo.gkvs = getRandomId()
    fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
    product.uploadTime = getcurDate()
    fs.writeFile(getAppLocalPath()+'dbson/PublicRectification.dbson', JSON.stringify(product), function (err) {
      if (err) {
        resolve(0)
        return
      }
      resolve(1)
    })
  })
}
// 整改公开查询
export const getRectification = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/PublicRectification.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || {})
    })
  })
}
// 新增/修改整改报告详情
export const addRectificationReport = (product) => {
  return new Promise((resolve, reject) => {
    let userinfo = getUser()
    // 保存版本信息
    userinfo.bgvs = getRandomId()
    fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
    // eslint-disable-next-line node/handle-callback-err
    if (product != null) {
      product.uploadTime = getcurDate()
      fs.writeFile(getAppLocalPath()+'dbson/RectificationReport.dbson', JSON.stringify(product), function (err) {
        if (err) {
          resolve(0)
          return
        }
        resolve(1)
      })
    }
  })
}
// 新增/修改整改报告列表
export const addRectificationReportList = (product) => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationReportList.dbson', 'utf-8', function(err, dataStr) {
      const option = {
        flag: 'w'
      }
      const list = JSON.parse(dataStr)
      // 读取记录,判断是否存在
      if (dataStr.indexOf(product.id)) {
        // 存在更新
        for (let i = 0; i < list.length; i++) {
          if (product.id === list[i].id) {
            product.uploadTime = getcurDate()
            const updatelist = JSON.stringify(product, null, 2)
            fs.writeFile(getAppLocalPath()+'dbson/RectificationReportList.dbson', updatelist, option, function (err) {
              if (err) {
                resolve(0)
                return
              }
              resolve(1)
            })
          }
        }
      } else {
        // 不存在新增
        const list = JSON.parse(dataStr)
        product.uploadTime = getcurDate()
        list.push(product)
        fs.writeFile(getAppLocalPath()+'dbson/RectificationReportList.dbson', JSON.stringify(list), function (err) {
          if (err) {
            resolve(0)
            return
          }
          resolve(1)
        })
      }
    })
  })
}
// 查询整改公开
export const getPublicRectification = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/PublicRectification.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })
  })
}
// 查询整改公开记录
export const getPublicRectificationSpjl = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/PublicRectification.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })
  })
}
// 新增/修改整改公开
export const addPublicRectification = (product) => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/PublicRectification.dbson', 'utf-8', function(err, dataStr) {
      const option = {
        flag: 'w'
      }
      const list = JSON.parse(dataStr)
      // 读取记录,判断是否存在
      if (dataStr.indexOf(product.id)) {
        // 存在更新
        for (let i = 0; i < list.length; i++) {
          if (product.id === list[i].id) {
            product.uploadTime = getcurDate()
            const updatelist = JSON.stringify(product, null, 2)
            fs.writeFile(getAppLocalPath()+'dbson/PublicRectification.dbson', updatelist, option, function (err) {
              if (err) {
                resolve(0)
                return
              }
              resolve(1)
            })
          }
        }
      } else {
        // 不存在新增
        const list = JSON.parse(dataStr)
        product.uploadTime = getcurDate()
        list.push(product)
        fs.writeFile(getAppLocalPath()+'dbson/PublicRectification.dbson', JSON.stringify(list), function (err) {
          if (err) {
            resolve(0)
            return
          }
          resolve(1)
        })
      }
    })
  })
}
// 查询数据同步
export const getDataSynchronization = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/DataSynchronization.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })

    // let db = conn()
    // db.all('select * from DataSynchronization', (err, rows) => {
    //   if (err) reject(err)
    //   resolve(rows || [])
    // })
  })
}
// 查询导入导出
export const getImportAndExportRecords = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/ImportAndExportRecords.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr==""?"[]":dataStr)
      let lsarr = list.filter(function(value){
        //筛选条件
        return value.jlid===getJLID()||value.jlid===""
      })
      resolve(lsarr || [])
    })
  })
}
// 上传文件
export const getuploadFileInfo = (product) => {

  //console.log(getLengthId(19))
  // 获取保存路径
  return new Promise((resolve, reject) => {
    let filepath = ''
    // eslint-disable-next-line node/handle-callback-err
    filepath = getSystemDir()
    console.log("f-path---",filepath)
    let uuid = generateUUID()
    // 设置保存路径
    const targetFolder = filepath
    const oldFilePath = path.resolve(product.path)
    const OriginFile = path.resolve(oldFilePath)
    const CopyFile = path.resolve(targetFolder, product.name)
    // 复制文件并重命名
    fs.copyFileSync(OriginFile, CopyFile)
    // resolve({
    //   fileid: uuid,
    //   filename: product.name,
    //   filepath: CopyFile
    // })
    console.log("f-path2---",CopyFile)
    let ret = {
      uid: uuid,
      name: product.name,
      url: CopyFile,
      status: 'done',
      filesize: product.size,
      updateTime: getcurDate()
    }
    resolve(ret)
  })
}
// 解析文件
export const exposeExcel = (product) => {
  console.log(product)
  // 获取保存路径
  return new Promise((resolve, reject) => {
    // 解析文件
    // 读取并解析excel模板
    // eslint-disable-next-line node/handle-callback-err
    // 存储整改内容excel
    getExcelDatas(product.file.path)
    resolve(1)
  })
}

// 获前存储路径
function getSystemDir() {
  let  paths = path.resolve('./chrtc')
  // 获取保存路径
  // eslint-disable-next-line node/handle-callback-err
  if(fs.existsSync(paths)) {
    return paths
  }
  fs.mkdirSync(paths)
  return paths
}
export const getTempletes = () => {
  return new Promise((resolve, reject) => {
    let user = fs.readFileSync(getAppLocalPath()+'dbson/User.dbson', 'utf-8')
    let usertmp = JSON.parse(user)
    let tmpname = usertmp.tmppath.slice(usertmp.tmppath.lastIndexOf('.') + 1)
    usertmp.tmpname = tmpname
    resolve(usertmp)
  })
}
//获取反馈意见文件
export const getFKdocs = () => {
  return new Promise((resolve, reject) => {
    let user = fs.readFileSync(getAppLocalPath()+'dbson/User.dbson', 'utf-8')
    let usertmp = JSON.parse(user)
    let doc = usertmp.fdoc
    resolve(usertmp)
  })
}
function mkdir(dirname) {
  if (fs.existsSync(dirname)) {
    console.log('创建失败1')
    return true
  } else {
    console.log('创建失败2')
    if (mkdir(path.dirname(dirname))) {
      console.log('创建失败3')
      fs.mkdirSync(dirname)
      return true
    }
  }
}
// 上传文件 -all
export const uploadFile = (product) => {
  console.log(product)
  // 获取保存路径
  return new Promise((resolve, reject) => {
    let filepath = ''
    let companyId = ''
    let companyName = ''
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/Filepath.dbson', 'utf-8', function(err, dataStr) {
      filepath = dataStr.split('=')[1].trim()
      // if (filepath === undefined && !fs.existsSync(filepath)) {
      mkdir(filepath)
      // }
      console.log(filepath)
      let uuid = getNowMilliSecond()
      let fileExt = product.name.slice(product.name.lastIndexOf('.') + 1)
      // 设置保存路径
      const targetFolder = filepath
      const oldFilePath = path.resolve(product.path)
      const OriginFile = path.resolve(oldFilePath)
      const CopyFile = path.resolve(targetFolder, `${uuid}.${fileExt}`)
      // 复制文件并重命名
      fs.copyFileSync(OriginFile, CopyFile)
      // 解压缩文件
      compressing.zip.uncompress(CopyFile, filepath + '/' + uuid).then((res) => {
        resolve({
          id: uuid,
          name: product.name,
          path: targetFolder
        })
        // 解析文件
        const feedbackpath = deepGetFile(filepath + '/' + uuid, 'fkyjxqb_')
        // 解析模板文件地址
        const teppath = deepGetFile(filepath + '/' + uuid, 'fkyjb_')
        // 解析文件数据
        const sysfilepath = deepGetFile(filepath + '/' + uuid, 'w_cruising_until_file_dir')
        let userinfo = getUser()
        let compjson = fs.readFileSync(teppath[0], 'utf-8')
        let fkDocid = JSON.parse(compjson).data[0].f_fkyjfj_[0].f_file_id_
        userinfo.compName = JSON.parse(compjson).data[0].f_xczdx_name_
        console.log('back----'+feedbackpath[0])
        // 清空文件
        clearFileConList(getAppLocalPath()+'dbson/Feedback.dbson')
        clearFileCon(getAppLocalPath()+'dbson/RectificationLedger.dbson')
        clearFileCon(getAppLocalPath()+'dbson/RectificationPlan.dbson')
        clearFileCon(getAppLocalPath()+'dbson/RectificationReport.dbson')
        clearFileCon(getAppLocalPath()+'dbson/PublicRectification.dbson')
        clearFileConList(getAppLocalPath()+'dbson/RectificationLedgerImports.dbson')
        clearFileConList(getAppLocalPath()+'dbson/RectificationMeeting.dbson')
        // 读取反馈意见并保存文件
        // eslint-disable-next-line node/handle-callback-err
        if(fs.existsSync(feedbackpath[0])) {
          let dataStr = fs.readFileSync(feedbackpath[0], 'utf-8')
          let localfeeback = []
          let listfeedback = (JSON.parse(dataStr)).data
          console.log(listfeedback)
          // eslint-disable-next-line no-empty
          for (let i = 0; i < listfeedback.length; i++) {
            let feedbackjson = new FeedbackClass()
            feedbackjson.setId(listfeedback[i].id_)
            feedbackjson.setremake(listfeedback[i].f_bz_)
            feedbackjson.setProblems(listfeedback[i].f_jtwt_)
            feedbackjson.setconcreteProblems(listfeedback[i].f_wtfm_)
            feedbackjson.setProblemClassification(listfeedback[i].f_wtfl_)
            feedbackjson.setremake(listfeedback[i].f_bz_)
            localfeeback.push(feedbackjson)
            companyId = listfeedback[i].f_xczdx_ref_id_
          }
          fs.writeFileSync(getAppLocalPath()+'dbson/Feedback.dbson', JSON.stringify(localfeeback))
          // 保存版本信息
          if (userinfo.yjvs === undefined) {
            userinfo.yjvs = getRandomId()
            userinfo.favs = getRandomId()
            userinfo.tzvs = getRandomId()
            userinfo.bgvs = getRandomId()
            userinfo.gkvs = getRandomId()
            userinfo.zlvs = getRandomId()
            userinfo.importTime = formatDate(new Date(), 'Y-M-D')
            fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
          }
        }
        //id不同，清掉数据
        if(companyId != userinfo.companyId){
          clearFileConList(getAppLocalPath()+'dbson/ImportAndExportRecords.dbson')
          clearFileConList(getAppLocalPath()+'dbson/AccessToMaterials.dbson')
          clearFileCon(getAppLocalPath()+'dbson/SysFileLists.dbson')
          // 读取系统文件类型文件夹并保存
          // eslint-disable-next-line node/handle-callback-err
          let dataStr = fs.readFileSync(sysfilepath[0], 'utf-8')
          let listsysfile = JSON.parse(dataStr)
          //筛选顶级文件夹
          let topfolder = []
          let otherfolder = []
          listsysfile.data.forEach(item=>{
            if(item.parent_id_ === item.f_patrol_object_id_){
              topfolder.push(item)
            }else{
              otherfolder.push(item)
            }
          })
          listsysfile.data = topfolder
          fs.writeFile(getAppLocalPath()+'dbson/SysFileLists.dbson', JSON.stringify(listsysfile, null, 2), function (err) {
            if (err) {
              resolve(0)
              return
            }
            //将非顶级文件夹，存储到文件列表中
            let dyfiles = fs.readFileSync(getAppLocalPath()+'dbson/AccessToMaterials.dbson','utf-8')
            let dyfilesjson = JSON.parse(dyfiles)
            dyfilesjson.concat(otherfolder)
            fs.writeFileSync(getAppLocalPath()+'dbson/AccessToMaterials.dbson',JSON.stringify(dyfilesjson))
          })

        }
        // 设置文件id，为导出文件唯一性做准备
        setFileId(uuid, companyId)
        // 解析模板地址，并解析文件
        if (teppath.length > 0 && teppath != undefined) {
          let tmpfile = fs.readFileSync(teppath[0], 'utf-8')
          let jsonfile = JSON.parse(tmpfile)
          let tmpname = jsonfile.data[0].f_xczdx_name_
          let tmppathid = jsonfile.finalFileId
          let tmppath = deepGetFile(filepath + '/' + uuid, tmppathid)[0]
          let fkdocpath = deepGetFile(filepath + '/' + uuid, fkDocid)[0]
          //复制一份台账文件，避免删除后丢失
          let distpath = filepath+'/' + path.basename(tmppath)
          fs.copyFileSync(tmppath, distpath)
          //处理反馈一i按文件同模板处理,并复制一份
          let fkpath = filepath+'/' + path.basename(fkdocpath)
          fs.copyFileSync(fkdocpath, fkpath)
          userinfo.fdoc=fkpath
          userinfo.fodcname = userinfo.compName+"_意见反馈"+"-"+getcurDate()
          // let user = fs.readFileSync('dbson/User.dbson', 'utf-8')
          // let userjson = JSON.parse(user)
          userinfo.tmpname = tmpname
          userinfo.tmppath = distpath
          // fs.writeFile('dbson/User.dbson', JSON.stringify(userjson))
          // eslint-disable-next-line node/handle-callback-err
          console.log(userinfo)
          fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
          // 读取时间整改方案，和整改报告时间
          const zqp = deepGetFile(filepath + '/' + uuid, 'w_yjpz')
          const zqdatep = deepGetFile(filepath + '/' + uuid, 'yjfk_')

          if (zqp !== undefined && zqdatep !== undefined) {
            let tmpfile = fs.readFileSync(zqdatep[0], 'utf-8')
            let tmpzqs = fs.readFileSync(zqp[0], 'utf-8')
            let timefa, timebg , fyjtime , byjtime
            let datelast = {}
            let dates = (JSON.parse(tmpfile)).data[0].f_yjrq_
            // eslint-disable-next-line no-empty-pattern
            let jsonpz = (JSON.parse(tmpzqs))
            let pz = JSON.parse(jsonpz.data[0].f_yjpz_)
            console.log('pz-----' + pz.length)
            pz.forEach(sm => {
              console.log(sm)
              // 1 天 2 周 3 月
              let daydatelb = sm.yjMs
              // 数量
              let daysnuums = sm.yjSj
              // 分类  3 方案  6报告
              let type = sm.yjType
              if (type === '3') {
                // eslint-disable-next-line no-unused-vars
                timefa = getDateStr(dates, daysnuums, daydatelb)
                fyjtime = dates
              }
              if (type === '6') {
                // eslint-disable-next-line no-unused-vars
                timebg = getDateStr(dates, daysnuums, daydatelb)
                byjtime = dates
              }
            })
            // 保存时间
            datelast.fgtime = timefa
            datelast.bgtime = timebg
            datelast.fyjtime = fyjtime
            datelast.byjtime = byjtime
            console.log('datelast--' + datelast)
            fs.writeFileSync(getAppLocalPath()+'dbson/ZGDate.dbson', JSON.stringify(datelast))
          }

        }
        let node = {}
        node.id = getNowMilliSecond()
        node.type = '导入'
        node.module = '整改监督'
        node.date = getcurDate()
        node.file = product.name
        node.size = getFileSize(product.size)
        node.path = CopyFile
        node.fname = ''
        setNodeOfUpAndExport(node)
        resolve(1)
      }).catch((res) => {
        resolve(0)
      })
    })
  })
}

/* params:
*    startTime --- 指定日期
*    AddCount --- 指定天/月数
*    dayFlag --- 1为n天，2为n周,3为n月
* */
export  const getDateStr=(startTime, AddCount, dayFlag)=> {
  const dd = new Date(startTime)
  // 获取AddCount天、月后的日期
  if (dayFlag === '1') {
    dd.setDate(dd.getDate() + AddCount)
  } else if (dayFlag === '3') {
    dd.setMonth((dd.getMonth()) + AddCount)
  } else {
    dd.setDate(dd.getDate() + AddCount * 7)
  }
  return timeToStr(dd)
}
function timeToStr (time) {
  const Y = time.getFullYear() + '-'
  const M = (time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1) + '-'
  const D = (time.getDate() < 10 ? '0' + (time.getDate()) : time.getDate()) + ' '
  return Y + M + D
}
function getExcelDatas(filein) {
  let xlsx = require('node-xlsx')
  let obj = xlsx.parse(filein, { cellDates: true })
  console.log(obj)
  let datas = obj[0].data
  console.log(datas)
  // let xl = require('node-xlrd')
  // let datas = []
  // // eslint-disable-next-line node/handle-callback-err
  //   xl.open(filein, function(err, bk) {
  //     let shtCount = bk.sheet.count
  //     for (let sIdx = 0; sIdx < shtCount; sIdx++) {
  //       // console.log('sheet "%d" ', sIdx)
  //       // console.log('  check loaded : %s', bk.sheet.loaded(sIdx))
  //       let sht = bk.sheets[sIdx]
  //       let rCount = sht.row.count
  //       let cCount = sht.column.count
  //      // console.log('  name = %s; index = %d; rowCount = %d; columnCount = %d', sht.name, sIdx, rCount, cCount)
  //       for (let rIdx = 0; rIdx < rCount; rIdx++) { // rIdx：行数；cIdx：列数
  //         let data = []
  //         for (let cIdx = 0; cIdx < cCount; cIdx++) {
  //           try {
  //             data.push(sht.cell(rIdx, cIdx))
  //             /// console.log('  cell : row = %d, col = %d, value = "%s"', rIdx, cIdx, sht.cell(rIdx, cIdx))
  //           } catch (e) {
  //             // console.log(e.message)
  //           }
  //         }
  //         datas.push(data)
  //       }
  //     }
  //     // req.datas = datas
  //
  let list = []
  for (let i = 0; i < datas.length; i++) {
    // eslint-disable-next-line no-empty
    if (i > 2) {
      if (datas[i].length > 0) {
        let dbson = {
          zg_0: datas[i][0],
          zg_1: datas[i][1],
          zg_2: datas[i][2],
          zg_01: datas[i][3],
          zg_02: datas[i][4],
          zg_03: datas[i][5],
          zg_04: datas[i][6],
          zg_05: datas[i][7],
          zg_06: datas[i][8],
          zg_07: datas[i][9],
          zg_08: datas[i][10],
          zg_09: datas[i][11],
          zg_10: datas[i][12],
          zg_11: datas[i][13],
          zg_12: datas[i][14]
        }
        console.log(dbson)
        list.push(dbson)
      }
    }
  }
  fs.writeFileSync(getAppLocalPath()+'dbson/RectificationLedgerImports.dbson', JSON.stringify(list))
  //  })
  // const workBook = XLSX.readFile(file)
  // let name = workBook.SheetNames[0]
  // let sheet = workBook.Sheets[name]
  // let data = XLSX.utils.sheet_to_json(sheet)
  // console.log(data)
}
function formatDate(value, format) {
  const formatNumber = n => `0${n}`.slice(-2)
  const date = value
  const formatList = ['Y', 'M', 'D', 'h', 'm', 's']
  const resultList = []
  resultList.push(date.getFullYear().toString())
  resultList.push(formatNumber(date.getMonth() + 1))
  resultList.push(formatNumber(date.getDate()))
  resultList.push(formatNumber(date.getHours()))
  resultList.push(formatNumber(date.getMinutes()))
  resultList.push(formatNumber(date.getSeconds()))
  for (let i = 0; i < resultList.length; i++) {
    format = format.replace(formatList[i], resultList[i])
  }
  return format
}
export const getPlanAndReportTimes = () => {
  return new Promise((resolve, reject) => {
    let fjson = fs.readFileSync(getAppLocalPath()+'dbson/RectificationPlan.dbson', 'utf-8')
    let bjson = fs.readFileSync(getAppLocalPath()+'dbson/RectificationReport.dbson', 'utf-8')
    let time = {
      ft: JSON.parse(fjson).uploadTime,
      bt: JSON.parse(bjson).uploadTime
    }
    resolve(time)
  })
}

export const getFileSize=(limit)=> {
  let size
  if (limit < 0.1 * 1024) { // 小于0.1KB，则转化成B
    size = limit.toFixed(2) + 'B'
  } else if (limit < 0.1 * 1024 * 1024) { // 小于0.1MB，则转化成KB
    size = (limit / 1024).toFixed(2) + 'KB'
  } else if (limit < 0.1 * 1024 * 1024 * 1024) { // 小于0.1GB，则转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
  } else { // 其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }

  let sizeStr = size + '' // 转成字符串
  let index = sizeStr.indexOf('.') // 获取小数点处的索引
  let dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
  if (dou === '00') { // 判断后两位是否为00，如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}
/**
 * 删除文件夹功能
 * @param  {String} url  文件路径，绝对路径
 * @return {Null}
 */
function deleteDir(url, filename){
  var files = [];

  if( fs.existsSync(url) ) {  //判断给定的路径是否存在

    files = fs.readdirSync(url);   //返回文件和子目录的数组
    files.forEach(function(file,index){
      var curPath = path.join(url,file);

      if(fs.statSync(curPath).isDirectory()) { //同步读取文件夹文件，如果是文件夹，则函数回调
        deleteDir(curPath);
      } else {
        if(!curPath.includes(filename)){
          fs.unlinkSync(curPath);    //是指定文件，则删除
        }
      }
    });
    // fs.rmdirSync(url); //清除文件夹
  }else{
    console.log("给定的路径不存在！");
  }

}
// 导出所有提报
let filesdata = {
  pk: 'file_id_',
  dataSource: 'lanhai_system',
  tableDesc: '系统文件',
  tableName: 'sys_file',
  data: []
}
// 导出整改监督数据
export const exportAlls = () => {
  return new Promise((resolve, reject) => {
    try {
      // 初始化文件目录，清楚原有数据
      filesdata.data=[]
      const userinit = getUser()
      // 获取数据文件路径
      let spathinit = getSystemDir()
      // eslint-disable-next-line camelcase
      let file = deepGetDirectory(spathinit + '/' + userinit.fileid, 'file')
      let filepath = file[0].split('整改监督')[0] + '整改监督/file'
      var fileName = path.basename(userinit.tmppath);
      deleteDir(filepath,fileName)
      //删除后重建文件夹
      // fs.mkdirSync(filepath)
      // 导出研究整改
      exportYJZG(resolve)
      // 导出整改方案
      exportZGFA(resolve)
      // 导出整改台账
      exportZGTZ(resolve)
      // 导出整改报告
      exportZGBG(resolve)
      // 导出整改公开
      exportZGGK(resolve)
      // 存储关联文件json
      // 获取用户信息
      const user = getUser()
      // 获取数据文件路径
      let spath = getSystemDir()
      // eslint-disable-next-line camelcase
      let patrol_system = deepGetDirectory(spath + '/' + user.fileid, 'lanhai_system')
      let datapath = patrol_system[0].split('lanhai_system')[0] + 'lanhai_system'
      fs.writeFile(datapath + '/' + 'sys_file', JSON.stringify(filesdata), function (err) {
        if (err) throw err
        console.log('sys_file 创建成功.')
      })
      console.log(filesdata)

      // eslint-disable-next-line camelcase
      let patrol_systemdel = deepGetDirectory(spath + '/' + user.fileid, 'patrol_system')
      let datapathdel = patrol_systemdel[0].split('patrol_system')[0] + 'patrol_system'
      let esdatadir = deepGetDirectory(spath + '/' + user.fileid, 'esdata')
      console.log(esdatadir.length)
      let esdata = (esdatadir[0] === undefined && esdatadir.length === 0 ? '' : esdatadir[0].split('esdata')[0] + 'esdata')

      // 删除相关文件
      let fkyjb = (datapathdel === undefined ? '' : datapathdel + '/' + 'fkyjb_')
      let fkyjxqb = (datapathdel === undefined ? '' : datapathdel + '/' + '/' + 'fkyjxqb_')
      let mbpz = (datapathdel === undefined ? '' : datapathdel + '/' + 'mbpz_')
      let wdir = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_cruising_until_file_dir')
      // eslint-disable-next-line camelcase
      let w_yjpz = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_yjpz')
      let yjfk = (datapathdel === undefined ? '' : datapathdel + '/' + 'yjfk_')
      let fileesdata = (esdata === undefined ? '' : esdata + '/' + 'sys_file_esdata')
      let wfite = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_site_patrol_material')
      console.log('998----' + fileesdata)
      // eslint-disable-next-line no-unused-expressions
      fkyjb !== undefined && fs.existsSync(fkyjb) ? fs.unlinkSync(fkyjb) : ''
      // eslint-disable-next-line no-unused-expressions
      fkyjxqb !== undefined && fs.existsSync(fkyjxqb) ? fs.unlinkSync(fkyjxqb) : ''
      // eslint-disable-next-line no-unused-expressions
      mbpz !== undefined && fs.existsSync(mbpz) ? fs.unlinkSync(mbpz) : ''
      // eslint-disable-next-line no-unused-expressions
      wdir !== undefined && fs.existsSync(wdir) ? fs.unlinkSync(wdir) : ''
      // eslint-disable-next-line camelcase,no-unused-expressions
      w_yjpz !== undefined && fs.existsSync(w_yjpz) ? fs.unlinkSync(w_yjpz) : ''
      // eslint-disable-next-line no-unused-expressions
      yjfk !== undefined && fs.existsSync(yjfk) ? fs.unlinkSync(yjfk) : ''
      // eslint-disable-next-line no-unused-expressions
      wfite !== undefined && fs.existsSync(wfite) ? fs.unlinkSync(wfite) : ''
      // eslint-disable-next-line no-unused-expressions
      fileesdata !== undefined && fs.existsSync(fileesdata) ? fs.unlinkSync(fileesdata) : ''

      // 压缩文件
      let listpath = fs.readdirSync(spath + '/' + user.fileid)
      let listpathall = fs.readdirSync(spath + '/' + user.fileid + '/' + listpath[0])
      console.log(listpathall)
      if (fs.existsSync(spath + '/' + listpath[0] + '.zip')) {
        fs.unlinkSync(spath + '/' + listpath[0] + '.zip')
      }
      compressing.zip.compressDir(spath + '/' + user.fileid + '/' + listpath[0], spath + '/' + listpath[0] + '.zip').then(() => {
        console.log('压缩完成')
        let node = {}
        node.id = getNowMilliSecond()
        node.type = '导出'
        node.date = getcurDate()
        node.file = listpath[0] + '.zip'
        node.size = getFileSize(fs.statSync(spath + '/' + listpath[0] + '.zip').size)
        node.path = spath + '/' + listpath[0] + '.zip'
        node.module = '整改监督'
        node.status = 1
        node.fname = listpath[0] + '.zip'
        setNodeOfUpAndExport(node)

        console.log('fname---' + node.fname)
        resolve(node)
      }).catch(() => {
        console.log('压缩失败')
        // resolve(0)
      })
    } catch (e) {
      console.log(e)
      let node = {}
      node.status = 0
      resolve(node)
    }
  })
}
// 导出调阅资料
export const exportDYZLAllsv2 = (unitName) => {
  return new Promise((resolve, reject) => {
    try {
      let ids=getNowMilliSecond()
      fs.mkdirSync(getSystemDir()+"/"+ids)
      const file_list=JSON.parse(fs.readFileSync(getAppLocalPath()+"dbson/AccessToMaterials.dbson")==""?"[]":fs.readFileSync(getAppLocalPath()+"dbson/AccessToMaterials.dbson"))
      file_list.forEach(item=>{
        //复制文件
        let firname=item.dirname
        if(!fs.existsSync(getSystemDir()+"/"+ids+"/"+firname)){
          fs.mkdirSync(getSystemDir()+"/"+ids+"/"+firname)
        }
        fs.copyFileSync(item.filePath,getSystemDir()+"/"+ids+"/"+firname+"/"+(new Date(item.uploadTime)).getTime()+"@@@"+item.fileName)
      })
      const unit={
        unitName:unitName,
        fileCode:"e968bd64f25335cd4440aa8bb1adc052",
        fileDesc:"调阅资料"
      }
      //Readme.json
      fs.writeFileSync(getSystemDir()+"/"+ids+"/Readme.json",ecodeFile(JSON.stringify(unit)))
      //压缩文件
      const zippath = getSystemDir()+"/"+ids
      compressing.zip.compressDir(zippath, zippath+ '.zip').then(() => {
        let fileb = fs.createReadStream(zippath+ '.zip')
        streamToBuffer(fileb).then(res => {
          let data = res
          let contents = new Uint8Array(data.length)
          for (let i = 0; i < data.length; i++) {
            contents[i] = data[i]
          }
          encryptv2(new Blob([contents]),password,resolve,'导出',unitName+"_调阅资料_"+ids,"调阅资料")
        })
      })
      //resolve(1)
    }catch (e) {
      console.log("err==",e)
      resolve(0)
    }
  })
}
// 导出调阅资料
// 导出调阅资料
export const exportDYZLAllsvV2 = async (unitName,dirList,onProgress) => {
      let ids=getNowMilliSecond()
  const limit2GB=2147483648;
  let size=0
  for  (const dir of dirList) {
    for  (const item of dir.fileList) {
      size+=item.size
    }
  }
  if (size>=limit2GB){
return {
  code:0,
  msg:"文件大小超过2GB"}
  }
  let folderDir=ids+'/'
      let path = ""
      const blobWriter = new zip.BlobWriter("application/zip");
      const zipWriter = new zip.ZipWriter(blobWriter);
  await zipWriter.add(folderDir, null, { directory: true });
  const unit={
    unitName:unitName,
    fileCode:"e968bd64f25335cd4440aa8bb1adc052",
    fileDesc:"调阅资料"
  }
  //Readme.json
  JSON.stringify(unit)
  //2147483648


  const readme = new Blob([ecodeFile(JSON.stringify(unit))]);
  await zipWriter.add(folderDir+'Readme.json', new zip.BlobReader(readme));
  let percent=0
  for await (const dir of dirList) {
    console.log("目录",dir)
    const ddir =folderDir+dir.name+'/'
   //const ddir= iconv.decode(iconv.decode(folderDir+dir.name+'/', 'utf-8'),'utf-8')
    console.log('ddir',ddir)
    await zipWriter.add(ddir, null, { directory: true });
    for await (const item of dir.fileList) {
        const data= await fs.readFileSync(item.filePath)
        const BLOB = new Blob([data], { type: zip.getMimeType(item.fileName) });
        console.log('size',item.size)
        await zipWriter.add(ddir+(new Date(item.uploadTime)).getTime()+"@@@"+item.fileName, new zip.BlobReader(BLOB),{ password: password,onprogress(progress, total) {
          }
        });
    }

  }
  const folder=unitName + "_调阅资料_" + ids
  const zipData=  await zipWriter.close();
  const zipStr=await zipData.arrayBuffer()
 await fs.writeFileSync(getSystemDir() + "/" + folder + ".zip", new Uint8Array(zipStr));
  importAndOutRecordv2('调阅资料', getSystemDir() + "/" + folder + ".zip", folder + ".zip", '导出')
  return    {
    fname: folder + ".zip",
    data: zipData
  }
}
function encryptv2(file, password,relsove,type,folder,module) {
  const Minizip = require('minizip-asm.js')
  const lid= getNowMilliSecond()
  const fr = new FileReader()
  fr.onload = function(event) {
    try {
      const zip = new Minizip(new Uint8Array(event.target.result));
      const newZip = new Minizip();
      zip.list({encoding: "buffer"}).forEach(function(o) {
        //newZip.append(o.filepath, zip.extract(o.filepath), {password: password});
        newZip.append(iconv.encode(Buffer.from(o.filepath), 'gb2312'), zip.extract(o.filepath), {password: password});
      });
      fs.writeFileSync(getSystemDir()+"/"+folder+".zip", new Buffer(newZip.zip()));
      //conver2(getSystemDir()+"/"+folder+".zip",folder+".zip");
      importAndOutRecordv2(module,getSystemDir()+"/"+folder+".zip",folder+".zip",type)
      const res={
        fname:folder+".zip",
        path:getSystemDir()+"/"+folder+".zip"
      }
      relsove(res)
    } catch (e) {
      relsove(0)
      console.log("ps-2--",e)
    }
  }
  fr.readAsArrayBuffer(file);
}

function importAndOutRecordv2(module,path,fname,type){
  let node = {}
  node.id = getNowMilliSecond()
  node.type = type
  node.module = module
  node.date = getcurDate()
  node.file = fname
  node.path = path
  node.fname = fname
  //绑定结论组
  node.jlid=getJLID()
  setNodeOfUpAndExport(node)
}
// 导出调阅资料
export const exportDYZLAlls = () => {
  return new Promise((resolve, reject) => {
    try {
      filesdata.data=[]
      const userinit = getUser()
      // 获取数据文件路径
      let spathinit = getSystemDir()
      // eslint-disable-next-line camelcase
      let file = deepGetDirectory(spathinit + '/' + userinit.fileid, 'file')
      let filepath = file[0].split('整改监督')[0] + '整改监督/file'

      var fileName = path.basename(userinit.tmppath);

      deleteDir(filepath,fileName)
      //删除后重建文件夹
      //fs.mkdirSync(filepath)
      // 导出资料
      try {
        exportFileList(resolve)
      }catch (e) {
        console.log(e)
      }
      // 存储关联文件json
      // 获取用户信息
      const user = getUser()
      // 获取数据文件路径
      let spath = getSystemDir()
      // eslint-disable-next-line camelcase
      let patrol_system = deepGetDirectory(spath + '/' + user.fileid, 'lanhai_system')
      let datapath = patrol_system[0].split('lanhai_system')[0] + 'lanhai_system'
      fs.writeFile(datapath + '/' + 'sys_file', JSON.stringify(filesdata), function (err) {
        if (err) throw err
        console.log('sys_file 创建成功.')
      })
      console.log(filesdata)
      // eslint-disable-next-line camelcase
      let patrol_systemdel = deepGetDirectory(spath + '/' + user.fileid, 'patrol_system')
      let datapathdel = patrol_systemdel[0].split('patrol_system')[0] + 'patrol_system'
      let esdatadir = deepGetDirectory(spath + '/' + user.fileid, 'esdata')
      console.log(esdatadir.length)
      let esdata = (esdatadir[0] === undefined && esdatadir.length === 0 ? '' : esdatadir[0].split('esdata')[0] + 'esdata')
      // 删除相关文件
      let fkyjb = (datapathdel === undefined ? '' : datapathdel + '/' + 'fkyjb_')
      let fkyjxqb = (datapathdel === undefined ? '' : datapathdel + '/' + '/' + 'fkyjxqb_')
      let mbpz = (datapathdel === undefined ? '' : datapathdel + '/' + 'mbpz_')
      let wdir = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_cruising_until_file_dir')
      // eslint-disable-next-line camelcase
      let w_yjpz = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_yjpz')
      let yjfk = (datapathdel === undefined ? '' : datapathdel + '/' + 'yjfk_')
      let fileesdata = (esdata === undefined ? '' : esdata + '/' + 'sys_file_esdata')
      let bgpath = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_zgbg')
      let fapath = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_zgfa')
      let gkpath = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_zggk')
      let hypath = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_zghy')
      let tzpath = (datapathdel === undefined ? '' : datapathdel + '/' + 'w_zgtz')
      console.log('998----' + fileesdata)
      // eslint-disable-next-line no-unused-expressions
      fkyjb !== undefined && fs.existsSync(fkyjb) ? fs.unlinkSync(fkyjb) : ''
      // eslint-disable-next-line no-unused-expressions
      fkyjxqb !== undefined && fs.existsSync(fkyjxqb) ? fs.unlinkSync(fkyjxqb) : ''
      // eslint-disable-next-line no-unused-expressions
      mbpz !== undefined && fs.existsSync(mbpz) ? fs.unlinkSync(mbpz) : ''
      // eslint-disable-next-line no-unused-expressions
      // wdir !== undefined && fs.existsSync(wdir) ? fs.unlinkSync(wdir) : ''
      // eslint-disable-next-line camelcase,no-unused-expressions
      w_yjpz !== undefined && fs.existsSync(w_yjpz) ? fs.unlinkSync(w_yjpz) : ''
      // eslint-disable-next-line no-unused-expressions
      yjfk !== undefined && fs.existsSync(yjfk) ? fs.unlinkSync(yjfk) : ''
      // eslint-disable-next-line no-unused-expressions
      fileesdata !== undefined && fs.existsSync(fileesdata) ? fs.unlinkSync(fileesdata) : ''
      // eslint-disable-next-line no-unused-expressions
      bgpath !== undefined && fs.existsSync(bgpath) ? fs.unlinkSync(bgpath) : ''
      // eslint-disable-next-line no-unused-expressions
      fapath !== undefined && fs.existsSync(fapath) ? fs.unlinkSync(fapath) : ''
      // eslint-disable-next-line no-unused-expressions
      gkpath !== undefined && fs.existsSync(gkpath) ? fs.unlinkSync(gkpath) : ''
      // eslint-disable-next-line no-unused-expressions
      hypath !== undefined && fs.existsSync(hypath) ? fs.unlinkSync(hypath) : ''
      // eslint-disable-next-line no-unused-expressions
      tzpath !== undefined && fs.existsSync(tzpath) ? fs.unlinkSync(tzpath) : ''
      // 压缩文件
      let listpath = fs.readdirSync(spath + '/' + user.fileid)
      let listpathall = fs.readdirSync(spath + '/' + user.fileid + '/' + listpath[0])
      let datetime = formatDate(new Date(), 'YMDhms')
      let filename = user.compName + '_调阅资料_' + datetime
      console.log(listpathall)
      if (fs.existsSync(spath + '/' + listpath[0] + '.zip')) {
        fs.unlinkSync(spath + '/' + listpath[0] + '.zip')
      }
      console.log(spath + '/' + user.fileid + '/' + listpath[0])
      console.log(spath + '/' + filename + '.zip')
      compressing.zip.compressDir(spath + '/' + user.fileid + '/' + listpath[0], spath + '/' + filename + '.zip').then(() => {
        console.log('压缩完成')
        let node = {}
        node.id = getNowMilliSecond()
        node.type = '导出'
        node.date = getcurDate()
        node.file = filename + '.zip'
        node.size = getFileSize(fs.statSync(spath + '/' + filename + '.zip').size)
        node.path = spath + '/' + filename + '.zip'
        node.status = 1
        node.module = '调阅资料'
        node.fname = filename + '.zip'
        console.log('fname---' + node.fname)
        setNodeOfUpAndExport(node)
        resolve(node)
      }).catch(e => {
        console.log('压缩失败')
        // resolve(0)
      })
    } catch (e) {
      let node = {}
      node.status = 1
      resolve(node)
    }
  })
}
// 导出研究整改
function exportYJZG(resolve) {
// 获取用户信息
  const user = getUser()
  // 获取数据文件路径
  let spath = getSystemDir()
  // eslint-disable-next-line camelcase
  let patrol_system = deepGetDirectory(spath + '/' + user.fileid, 'patrol_system')
  let file = deepGetDirectory(spath + '/' + user.fileid, 'file')
  let datapath = patrol_system[0].split('patrol_system')[0] + 'patrol_system'
  let filepath = file[0].split('整改监督')[0] + '整改监督/file'
  console.log(datapath + '\n' + filepath)
  // 研究整改工作数据组装并生成文件
  let newZGHYfile = 'w_zghy'
  let zggzdbson = fs.readFileSync('dbson/RectificationMeeting.dbson', 'utf-8')
  let newzggzdbson = {
    pk: 'ID_',
    dataSource: 'patrol_system',
    tableDesc: '研究整改工作',
    tableName: 'w_zghy',
    data: []
  }
  let zzgzdata = JSON.parse(zggzdbson)
  // eslint-disable-next-line no-unused-vars,no-empty
  if (zzgzdata !== undefined) {
    zzgzdata.forEach(item => {
      let filelast = []
      // 文件数据组装
      let filelist = item.fileList
      // eslint-disable-next-line no-unused-vars,no-empty
      if (filelist !== undefined) {
        filelist.forEach(itemf => {
          let fileExt = itemf.name.slice(itemf.name.lastIndexOf('.') + 1)
          let filemore = {
            FILE_ID_: itemf.uid,
            file_name_: itemf.name,
            new_fname_: `${itemf.uid}.${fileExt}`,
            PATH_: 'admin/202306/' + `${itemf.uid}.${fileExt}`,
            EXT_: fileExt,
            total_bytes_: itemf.filesize,
            del_status_: 'undeleted',
            cover_status_: 'NO',
            file_system_: 'file',
            create_by_: '1',
            create_time_: getcurDate(),
            encrypt: 0
          }
          filesdata.data.push(filemore)
          let fjson =
            {
              fileName: itemf.name,
              timestamp: getNowMilliSecond(),
              size: itemf.filesize,
              ext: true,
              permission: '',
              fileId: itemf.uid,
              showSize: getFileSize(itemf.filesize),
              fileClass: 'iconBox excelBox',
              auth: {
                add: true,
                read: true,
                edit: true,
                delete: true
              }
            }
          filelast.push(fjson)
          // 复制文件并重命名
          if (itemf.url != null && fs.existsSync(itemf.url)) {
            fs.copyFileSync(itemf.url, filepath + '/' + `${itemf.uid}.${fileExt}`)
          }
        })
      }
      // 组装外层数据
      let jsonitem = {
        del_flag_: '1',
        create_by_: '1',
        id_: item.id,
        serial_num_: 1,
        create_time_: item.dateOfMeeting,
        f_xczdx_ref_id_: user.companyId,
        f_hyzt_: item.theme,
        f_hylx_: (item.meetingType === undefined || item.meetingType === null) ? '' : item.meetingType,
        f_hyrq_: item.dateOfMeeting,
        f_hykssj_: item.startMeetingTime,
        f_hyjssj_: item.endMeetingTime,
        f_zcr_: item.host,
        f_chry_: item.participants,
        f_hytg_: item.meetingSummary,
        f_version_: user.yjvs,
        f_hycl_: filelast
      }
      // 塞入数据
      newzggzdbson.data.push(jsonitem)
    })
  }
  console.log(newzggzdbson)
  // 创建json data 映射文件，并写入数据
  fs.writeFile(datapath + '/' + newZGHYfile, JSON.stringify(newzggzdbson), function (err) {
    if (err) throw err
    console.log(`${newZGHYfile}  创建成功.`)
  })
  return filesdata
}
// 导出整改方案
function exportZGFA(resolve) {
// 获取用户信息
  const user = getUser()
  // 获取数据文件路径
  let spath = getSystemDir()
  // eslint-disable-next-line camelcase
  let patrol_system = deepGetDirectory(spath + '/' + user.fileid, 'patrol_system')
  let file = deepGetDirectory(spath + '/' + user.fileid, 'file')
  let datapath = patrol_system[0].split('patrol_system')[0] + 'patrol_system'
  let filepath = file[0].split('整改监督')[0] + '整改监督/file'
  console.log(datapath + '\n' + filepath)
  // 研究整改工作数据组装并生成文件
  let newZGFAfile = 'w_zgfa'
  let zgfadbson = fs.readFileSync('dbson/RectificationPlan.dbson', 'utf-8')
  let newzgfadbson = {
    pk: 'ID_',
    dataSource: 'patrol_system',
    tableDesc: '整改方案',
    tableName: 'w_zgfa',
    data: []
  }
  let zgfadata = JSON.parse(zgfadbson)
  // eslint-disable-next-line no-unused-vars,no-empty
  let filelast = []
  // 文件数据组装
  let filelist = zgfadata.fileList
  // eslint-disable-next-line no-unused-vars,no-empty
  if (filelist != null) {
    filelist.forEach(itemf => {
      let fileExt = itemf.name.slice(itemf.name.lastIndexOf('.') + 1)
      let filemore = {
        FILE_ID_: itemf.uid,
        file_name_: itemf.name,
        new_fname_: `${itemf.uid}.${fileExt}`,
        PATH_: 'admin/202306/' + `${itemf.uid}.${fileExt}`,
        EXT_: fileExt,
        total_bytes_: itemf.filesize,
        del_status_: 'undeleted',
        cover_status_: 'NO',
        file_system_: 'file',
        create_by_: '1',
        create_time_: getcurDate(),
        encrypt: 0
      }
      filesdata.data.push(filemore)
      let fjson =
        {
          fileName: itemf.name,
          timestamp: getNowMilliSecond(),
          size: itemf.filesize,
          ext: true,
          permission: '',
          fileId: itemf.uid,
          showSize: getFileSize(itemf.filesize),
          fileClass: 'iconBox excelBox',
          auth: {
            add: true,
            read: true,
            edit: true,
            delete: true
          }
        }
      filelast.push(fjson)
      // 复制文件并重命名
      if (itemf.url != null && fs.existsSync(itemf.url)) {
        fs.copyFileSync(itemf.url, filepath + '/' + `${itemf.uid}.${fileExt}`)
      }
    })
  }
  // 组装外层数据
  let jsonitem = {
    f_xczdx_ref_id_: user.companyId,
    del_flag_: '1',
    create_by_: '1',
    id_: user.companyId,
    serial_num_: 1,
    create_time_: zgfadata.uploadTime,
    f_version_: user.favs,
    f_zgfa_: filelast
  }
  // 塞入数据
  newzgfadbson.data.push(jsonitem)
  console.log(newzgfadbson)
  // 创建json data 映射文件，并写入数据
  fs.writeFile(datapath + '/' + newZGFAfile, JSON.stringify(newzgfadbson), function (err) {
    if (err) throw err
    console.log(`${newZGFAfile}  创建成功.`)
  })
  return filesdata
}
// 导出整改台账
function exportZGTZ(resolve) {
// 获取用户信息
  const user = getUser()
  // 获取数据文件路径
  let spath = getSystemDir()
  // eslint-disable-next-line camelcase
  let patrol_system = deepGetDirectory(spath + '/' + user.fileid, 'patrol_system')
  let file = deepGetDirectory(spath + '/' + user.fileid, 'file')
  let datapath = patrol_system[0].split('patrol_system')[0] + 'patrol_system'
  let filepath = file[0].split('整改监督')[0] + '整改监督/file'
  console.log(datapath + '\n' + filepath)
  // 研究整改工作数据组装并生成文件
  let newzgtzfile = 'w_zgtz'
  let zgtzdbson = fs.readFileSync('dbson/RectificationLedger.dbson', 'utf-8')
  let newzgtzdbson = {
    pk: 'ID_',
    dataSource: 'patrol_system',
    tableDesc: '整改台账',
    tableName: 'w_zgtz',
    data: []
  }
  let zgtzdata = JSON.parse(zgtzdbson)
  // eslint-disable-next-line no-unused-vars,no-empty
  let filelast = []
  // 文件数据组装
  let filelist = zgtzdata.fileList
  // eslint-disable-next-line no-unused-vars,no-empty
  if (filelist !== undefined) {
    filelist.forEach(itemf => {
      let fileExt = itemf.name.slice(itemf.name.lastIndexOf('.') + 1)
      let filemore = {
        FILE_ID_: itemf.uid,
        file_name_: itemf.name,
        new_fname_: `${itemf.uid}.${fileExt}`,
        PATH_: 'admin/202306/' + `${itemf.uid}.${fileExt}`,
        EXT_: fileExt,
        total_bytes_: itemf.filesize,
        del_status_: 'undeleted',
        cover_status_: 'NO',
        file_system_: 'file',
        create_by_: '1',
        create_time_: itemf.uploadTime,
        encrypt: 0
      }
      filesdata.data.push(filemore)
      let fjson =
        {
          fileName: itemf.name,
          timestamp: getNowMilliSecond(),
          size: itemf.filesize,
          ext: true,
          permission: '',
          fileId: itemf.uid,
          showSize: getFileSize(itemf.filesize),
          fileClass: 'iconBox excelBox',
          auth: {
            add: true,
            read: true,
            edit: true,
            delete: true
          }
        }
      filelast.push(fjson)
      // 复制文件并重命名
      if (itemf.url != null && fs.existsSync(itemf.url)) {
        fs.copyFileSync(itemf.url, filepath + '/' + `${itemf.uid}.${fileExt}`)
      }
    })
  }
  // 组装外层数据
  let jsonitem = {
    f_xczdx_ref_id_: user.companyId,
    del_flag_: '1',
    create_by_: '1',
    id_: user.companyId,
    serial_num_: 1,
    create_time_: getcurDate(),
    f_version_: user.tzvs,
    f_zgtz_: filelast
  }
  // 塞入数据
  newzgtzdbson.data.push(jsonitem)
  console.log(newzgtzdbson)
  // 创建json data 映射文件，并写入数据
  fs.writeFile(datapath + '/' + newzgtzfile, JSON.stringify(newzgtzdbson), function (err) {
    if (err) throw err
    console.log(`${newzgtzfile}  创建成功.`)
  })
}
// 导出整改报告
function exportZGBG(resolve) {
// 获取用户信息
  const user = getUser()
  // 获取数据文件路径
  let spath = getSystemDir()
  // eslint-disable-next-line camelcase
  let patrol_system = deepGetDirectory(spath + '/' + user.fileid, 'patrol_system')
  let file = deepGetDirectory(spath + '/' + user.fileid, 'file')
  let datapath = patrol_system[0].split('patrol_system')[0] + 'patrol_system'
  let filepath = file[0].split('整改监督')[0] + '整改监督/file'
  console.log(datapath + '\n' + filepath)
  // 研究整改工作数据组装并生成文件
  let newzgbgfile = 'w_zgbg'
  let zgbgdbson = fs.readFileSync('dbson/RectificationReport.dbson', 'utf-8')
  let newzgbgdbson = {
    pk: 'ID_',
    dataSource: 'patrol_system',
    tableDesc: '整改报告',
    tableName: 'w_zgbg',
    data: []
  }
  let zgbgdata = JSON.parse(zgbgdbson)
  // eslint-disable-next-line no-unused-vars,no-empty
  let filelast = []
  // 文件数据组装
  let filelist = zgbgdata.fileList
  // eslint-disable-next-line no-unused-vars,no-empty
  if (filelist != null) {
    filelist.forEach(itemf => {
      let fileExt = itemf.name.slice(itemf.name.lastIndexOf('.') + 1)
      let filemore = {
        FILE_ID_: itemf.uid,
        file_name_: itemf.name,
        new_fname_: `${itemf.uid}.${fileExt}`,
        PATH_: 'admin/202306/' + `${itemf.uid}.${fileExt}`,
        EXT_: fileExt,
        total_bytes_: itemf.filesize,
        del_status_: 'undeleted',
        cover_status_: 'NO',
        file_system_: 'file',
        create_by_: '1',
        create_time_: getcurDate(),
        encrypt: 0
      }
      filesdata.data.push(filemore)
      let fjson =
        {
          fileName: itemf.name,
          timestamp: getNowMilliSecond(),
          size: itemf.filesize,
          ext: true,
          permission: '',
          fileId: itemf.uid,
          showSize: getFileSize(itemf.filesize),
          fileClass: 'iconBox excelBox',
          auth: {
            add: true,
            read: true,
            edit: true,
            delete: true
          }
        }
      filelast.push(fjson)
      // 复制文件并重命名
      if (itemf.url != null && fs.existsSync(itemf.url)) {
        fs.copyFileSync(itemf.url, filepath + '/' + `${itemf.uid}.${fileExt}`)
      }
    })
  }
  // 组装外层数据
  let jsonitem = {
    f_xczdx_ref_id_: user.companyId,
    del_flag_: '1',
    create_by_: '1',
    id_: user.companyId,
    serial_num_: 1,
    create_time_: zgbgdata.uploadTime,
    f_version_: user.bgvs,
    f_zgbg_: filelast
  }
  // 塞入数据
  newzgbgdbson.data.push(jsonitem)
  console.log(newzgbgdbson)
  // 创建json data 映射文件，并写入数据
  fs.writeFile(datapath + '/' + newzgbgfile, JSON.stringify(newzgbgdbson), function (err) {
    if (err) throw err
    console.log(`${newzgbgfile}  创建成功.`)
  })
}
// 导出整改公开
function exportZGGK(resolve) {
// 获取用户信息
  const user = getUser()
  // 获取数据文件路径
  let spath = getSystemDir()
  // eslint-disable-next-line camelcase
  let patrol_system = deepGetDirectory(spath + '/' + user.fileid, 'patrol_system')
  let file = deepGetDirectory(spath + '/' + user.fileid, 'file')
  let datapath = patrol_system[0].split('patrol_system')[0] + 'patrol_system'
  let filepath = file[0].split('整改监督')[0] + '整改监督/file'
  console.log(datapath + '\n' + filepath)
  // 研究整改工作数据组装并生成文件
  let newzggkfile = 'w_zggk'
  let zggkdbson = fs.readFileSync(getAppLocalPath()+'dbson/PublicRectification.dbson', 'utf-8')
  let newzggkdbson = {
    pk: 'ID_',
    dataSource: 'patrol_system',
    tableDesc: '整改公开',
    tableName: 'w_zggk',
    data: [
    ]
  }
  let zggkdata = JSON.parse(zggkdbson)
  // eslint-disable-next-line camelcase
  let list_tb = zggkdata.fileList_tb
  // eslint-disable-next-line camelcase
  // let list_gk = zggkdata.fileList_gk
  let list_gk = zggkdata.fileList
  // eslint-disable-next-line camelcase
  let list_mark = zggkdata.fileList_mark
  // eslint-disable-next-line no-unused-vars,no-empty
  let filelast_tb = []
  let filelast_gk = []
  let filelast_mark = []
  // 通报文件数据组装
  // eslint-disable-next-line no-unused-vars,no-empty
  if (list_tb != undefined) {
    list_tb.forEach(itemf => {
      let fileExt = itemf.name.slice(itemf.name.lastIndexOf('.') + 1)
      let filemore = {
        FILE_ID_: itemf.uid,
        file_name_: itemf.name,
        new_fname_: `${itemf.uid}.${fileExt}`,
        PATH_: 'admin/202306/' + `${itemf.uid}.${fileExt}`,
        EXT_: fileExt,
        total_bytes_: itemf.filesize,
        del_status_: 'undeleted',
        cover_status_: 'NO',
        file_system_: 'file',
        create_by_: '1',
        create_time_: getcurDate(),
        encrypt: 0
      }
      filesdata.data.push(filemore)
      let fjson =
        {
          fileName: itemf.name,
          timestamp: getNowMilliSecond(),
          size: itemf.filesize,
          ext: true,
          permission: '',
          fileId: itemf.uid,
          showSize: getFileSize(itemf.filesize),
          fileClass: 'iconBox excelBox',
          auth: {
            add: true,
            read: true,
            edit: true,
            delete: true
          }
        }
      filelast_tb.push(fjson)
      // 复制文件并重命名
      if (itemf.url != null && fs.existsSync(itemf.url)) {
        fs.copyFileSync(itemf.url, filepath + '/' + `${itemf.uid}.${fileExt}`)
      }
    })
  }
  // eslint-disable-next-line camelcase
  if (list_gk !== undefined) {
    list_gk.forEach(itemf => {
      let fileExt = itemf.name.slice(itemf.name.lastIndexOf('.') + 1)
      let filemore = {
        FILE_ID_: itemf.uid,
        file_name_: itemf.name,
        new_fname_: `${itemf.uid}.${fileExt}`,
        PATH_: 'admin/202306/' + `${itemf.uid}.${fileExt}`,
        EXT_: fileExt,
        total_bytes_: itemf.filesize,
        del_status_: 'undeleted',
        cover_status_: 'NO',
        file_system_: 'file',
        create_by_: '1',
        create_time_: getcurDate(),
        encrypt: 0
      }
      filesdata.data.push(filemore)
      let fjson =
        {
          fileName: itemf.name,
          timestamp: getNowMilliSecond(),
          size: itemf.filesize,
          ext: true,
          permission: '',
          fileId: itemf.uid,
          showSize: getFileSize(itemf.filesize),
          fileClass: 'iconBox excelBox',
          auth: {
            add: true,
            read: true,
            edit: true,
            delete: true
          }
        }
      filelast_gk.push(fjson)
      // 复制文件并重命名
      if (itemf.url != null && fs.existsSync(itemf.url)) {
        fs.copyFileSync(itemf.url, filepath + '/' + `${itemf.uid}.${fileExt}`)
      }
    })
  }
  // eslint-disable-next-line camelcase
  if (list_tb !== undefined) {
    list_mark.forEach(itemf => {
      let fileExt = itemf.name.slice(itemf.name.lastIndexOf('.') + 1)
      let filemore = {
        file_id_: itemf.uid,
        file_name_: itemf.name,
        new_fname_: `${itemf.uid}.${fileExt}`,
        path_: 'admin/202306/' + `${itemf.uid}.${fileExt}`,
        ext_: fileExt,
        total_bytes_: itemf.filesize,
        del_status_: 'undeleted',
        cover_status_: 'NO',
        file_system_: 'file',
        create_by_: '1',
        create_time_: getcurDate(),
        encrypt: 0
      }
      filesdata.data.push(filemore)
      let fjson =
        {
          fileName: itemf.name,
          timestamp: getNowMilliSecond(),
          size: itemf.filesize,
          ext: true,
          permission: '',
          fileId: itemf.uid,
          showSize: getFileSize(itemf.filesize),
          fileClass: 'iconBox excelBox',
          auth: {
            add: true,
            read: true,
            edit: true,
            delete: true
          }
        }
      filelast_mark.push(fjson)
      // 复制文件并重命名
      if (itemf.url != null && fs.existsSync(itemf.url)) {
        fs.copyFileSync(itemf.url, filepath + '/' + `${itemf.uid}.${fileExt}`)
      }
    })
  }
  // 组装外层数据
  let jsonitem = {
    f_xczdx_ref_id_: user.companyId,
    del_flag_: '1',
    create_by_: '1',
    id_: user.companyId,
    serial_num_: 1,
    create_time_: zggkdata.uploadTime,
    f_version_: user.gkvs,
    f_dntbg_: filelast_tb,
    f_shgkg_: filelast_gk,
    f_sxsm_: filelast_mark
  }
  // 塞入数据
  newzggkdbson.data.push(jsonitem)
  console.log(newzggkdbson)
  // 创建json data 映射文件，并写入数据
  fs.writeFile(datapath + '/' + newzggkfile, JSON.stringify(newzggkdbson), function (err) {
    if (err) throw err
    console.log(`${newzggkfile}  创建成功.`)
  })
}
// 导出材料文件
function exportFileList(resolve) {
// 获取用户信息
  const user = getUser()
  // 获取数据文件路径
  let spath = getSystemDir()
  // eslint-disable-next-line camelcase
  let patrol_system = deepGetDirectory(spath + '/' + user.fileid, 'patrol_system')
  let file = deepGetDirectory(spath + '/' + user.fileid, 'file')
  let datapath = patrol_system[0].split('patrol_system')[0] + 'patrol_system'
  let filepath = file[0].split('整改监督')[0] + '整改监督/file'
  console.log(datapath + '\n' + filepath)
  // 研究整改工作数据组装并生成文件
  let newfilelistfile = 'w_site_patrol_material'
  let newfoldername = 'w_cruising_until_file_dir'
  let filelistdbson = fs.readFileSync(getAppLocalPath()+'dbson/AccessToMaterials.dbson', 'utf-8')
  let newfilelistdbson = {
    pk: 'ID_',
    dataSource: 'patrol_system',
    tableDesc: '文件列表',
    tableName: 'w_site_patrol_material',
    data: [
    ]
  }
  let filelistdata = JSON.parse(filelistdbson)
  // 通报文件数据组装
  // eslint-disable-next-line no-unused-vars,no-empty
  filelistdata.forEach(itemf => {
    if(itemf.fileType!='folder') {
      let fileExt = itemf.fileType
      let filemore = {
        FILE_ID_: itemf.id,
        file_name_: itemf.fileName,
        new_fname_: `${itemf.id}.${fileExt}`,
        PATH_: 'admin/202306/' + `${itemf.id}.${fileExt}`,
        EXT_: fileExt,
        total_bytes_: itemf.size,
        del_status_: 'undeleted',
        cover_status_: 'NO',
        file_system_: 'file',
        create_by_: '1',
        create_time_: getcurDate(),
        encrypt: 0
      }
      filesdata.data.push(filemore)
      let fjson =
        {
          fileName: itemf.fileName,
          timestamp: getNowMilliSecond(),
          size: itemf.size,
          ext: true,
          permission: '',
          fileId: itemf.id,
          showSize: getFileSize(itemf.size),
          fileClass: 'iconBox excelBox',
          auth: {
            add: true,
            read: true,
            edit: true,
            delete: true
          }
        }
      let fjsonlat =
        {
          id_: itemf.id,
          f_file_name_: itemf.fileName,
          f_belongs_directory_name_: itemf.dirname,
          f_file_: [],
          f_file_type_: itemf.fileType,
          f_file_size_: itemf.size,
          f_upload_people_: 1,
          f_upload_people__name: '管理员',
          f_inspected_units_name_: itemf.pname,
          f_belongs_directory_id_: itemf.documentsType,
          f_upload_time_: getcurDate(),
          create_time_: itemf.uploadTime,
          create_by_: 1,
          serial_num_: 1,
          del_flag_: 1,
          f_file_id_: itemf.id,
          f_belongs_resource_: itemf.mtype
        }
      //   console.log(fjsonlat)
      // console.log('--------000--------')
      fjsonlat.f_file_.push(fjson)
      // filelistlat.push(fjsonlat)
      newfilelistdbson.data.push(fjsonlat)
      // 复制文件并重命名
      if (itemf.filePath != null && fs.existsSync(itemf.filePath)) {
        fs.copyFileSync(itemf.filePath, filepath + '/' + `${itemf.id}.${fileExt}`)
      }
    }
  })
  let localfiles = fs.readFileSync(getAppLocalPath()+'dbson/SysFileLists.dbson','utf-8')
  let localfilefolder = fs.readFileSync(getAppLocalPath()+'dbson/AccessToMaterials.dbson','utf-8')
  let localfilefolderList = JSON.parse(localfilefolder)
  let localfilesList = JSON.parse(localfiles)
  let findex = localfilesList.data.length
  //文件夹数据操作
  localfilefolderList.forEach(fitem => {
    findex++
    if(fitem.fileType ==='folder') {
      let folder = {
        parent_id_: fitem.documentsType,
        del_flag_: "1",
        create_dep_id_: "1",
        f_patrol_object_name_: fitem.pname,
        create_by_: "1",
        id_: fitem.id,
        serial_num_: 1,
        tenant_id_: "1",
        f_directory_name_: fitem.fileName,
        create_time_: fitem.uploadTime,
        f_serial_number_: findex+'',
        f_term_id_: "1633009491647741953",
        update_time_: fitem.uploadTime,
        f_patrol_object_id_: "1668556221642231810",
        f_directory_type: "loanMaterial"
      }
      localfilesList.data.push(folder)
    }
  })
  console.log('1-----'+datapath + '/' + newfoldername)
  // 创建调阅资料文件夹映射，并写入数据
  fs.writeFileSync(datapath + '/' + newfoldername, JSON.stringify(localfilesList))
  // 创建调阅资料文件映射文件，并写入数据
  fs.writeFileSync(datapath + '/' + newfilelistfile, JSON.stringify(newfilelistdbson))
}

// 保存导入导出记录
export  const setNodeOfUpAndExport=(node)=> {
  console.log(node)
  let nodes = fs.readFileSync(getAppLocalPath()+'dbson/ImportAndExportRecords.dbson', 'utf-8')
  let jsonStr = nodes==""?[]:JSON.parse(nodes)
  jsonStr.push(node)
  console.log("imp--",jsonStr.length)
  fs.writeFileSync(getAppLocalPath()+'dbson/ImportAndExportRecords.dbson', JSON.stringify(jsonStr))
}
// 获取整改台账模板内容
export const getTmpleteteInfos = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/RectificationLedgerImports.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })
  })
}
// 获取调查资料文件夹
export const getAccessFileDir = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/SysFileLists.dbson', 'utf-8', function(err, dataStr) {
      console.log("j-dy----",dataStr)
      const list = JSON.parse(dataStr)
      resolve(list.data || [])
    })
  })
}
// 查询调阅资料
export const getAccessToMaterials = () => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/AccessToMaterials.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      resolve(list || [])
    })
  })
}
// 调阅资料上传
export const uploadAccessToMaterials = (product) => {
  return new Promise((resolve, reject) => {
    let userinfo = getUser()
    // 保存版本信息
    userinfo.zlvs = getRandomId()
    fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
    let uuid = generateUUID()
    let fileExt = product.name.slice(product.name.lastIndexOf('.') + 1)
    // 设置保存路径
    const targetFolder = path.join(process.resourcesPath)
    const oldFilePath = path.resolve(product.path)
    const OriginFile = path.resolve(oldFilePath)
    const CopyFile = path.resolve(targetFolder, `${uuid}.${fileExt}`)
    fs.copyFileSync(OriginFile, CopyFile)
    resolve({
      id: uuid,
      fileType: fileExt,
      fileName: product.name,
      filePath: path.resolve(targetFolder, `${uuid}.${fileExt}`),
      documentsType: product.documentsType,
      uploadTime: getcurDate()
    })
  })
}
// 新增调阅资料
export const  addAccessToMaterials = (product) => {
  return new Promise((resolve, reject) => {
    console.log("pss---",product)
    let userinfo = getUser()
    // 保存版本信息
    userinfo.zlvs = getRandomId()
    fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
    // eslint-disable-next-line node/handle-callback-err
    let dataStr = fs.readFileSync(getAppLocalPath()+'dbson/AccessToMaterials.dbson', 'utf-8')
    const list = JSON.parse(dataStr)

    const lasr = list.filter(item=>{
      return item.documentsType===product.documentsType && item.fileName===product.fileName
    })

    if(lasr.length>0){
      resolve(2)
      return
    }

    product.uploadTime = getcurDate()
    product.fid = getNowMilliSecond()
    list.push(product)
    fs.writeFileSync(getAppLocalPath()+'dbson/AccessToMaterials.dbson', JSON.stringify(list))
    resolve(1)
  })
}
// 删除调阅资料
export const delAccessToMaterials = (id, dirid) => {
  return new Promise((resolve, reject) => {
    let userinfo = getUser()
    // 保存版本信息
    userinfo.zlvs = getRandomId()
    fs.writeFileSync(getAppLocalPath()+'dbson/User.dbson', JSON.stringify(userinfo))
    // eslint-disable-next-line node/handle-callback-err
    fs.readFile(getAppLocalPath()+'dbson/AccessToMaterials.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      list.forEach(item => {
        // eslint-disable-next-line no-cond-assign
        if (item.fid === id && item.documentsType === dirid) {
          let index = list.indexOf(item)
          if (index > -1) {
            list.splice(index, 1)
          }
        }
      })
      fs.writeFile(getAppLocalPath()+'dbson/AccessToMaterials.dbson', JSON.stringify(list), function (err) {
        if (err) {
          resolve(0)
          return
        }
        resolve(1)
      })
    })
  })
}
// 将文件转为二进制

export function fileParse(file, type) {
  const caseType = {
    base64: 'readAsDataURL',
    buffer: 'readAsArrayBuffer'
  }
  const fileRead = new FileReader()
  return new Promise(resolve => {
    fileRead[caseType[type]](file)
    fileRead.onload = (res) => {
      resolve(res.target.result)
    }
  })
}
//文件数据流
export function streamToBuffer(stream) {
  return new Promise((resolve, reject) => {
    let buffers = []
    stream.on('error', reject)
    stream.on('data', (data) => buffers.push(data))
    stream.on('end', () => resolve(Buffer.concat(buffers)))
  })
}
//删除报告列表
export function deleteReport(record) {
  return new Promise((resolve, reject) => {
    clearFileCon(getAppLocalPath()+'dbson/RectificationReport.dbson')
    resolve(1)
  })
}
//删除方案列表
export function deletePlan(record) {
  return new Promise((resolve, reject) => {
    clearFileCon(getAppLocalPath()+'dbson/RectificationPlan.dbson')
    resolve(1)
  })
}
//删除方案列表
export function deleteGK(product) {
  return new Promise((resolve, reject) => {
    fs.readFile(getAppLocalPath()+'dbson/PublicRectification.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      // eslint-disable-next-line no-empty
      for (let i = 0; i < list.fileList.length; i++) {
        // eslint-disable-next-line no-empty
        if (list.fileList[i].uid === product.uid) {
          list.fileList.splice(i, i + 1)
        }
      }
      fs.writeFile(getAppLocalPath()+'dbson/PublicRectification.dbson', JSON.stringify(list), function(err) {
        if (err) {
          resolve(0)
          return
        }
        resolve(1)
      })
    })
  })
}
//新建文件夹
export function makeFolder(product) {
  return new Promise((resolve, reject) => {
    //新增文件表
    fs.readFile(getAppLocalPath()+'dbson/AccessToMaterials.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      // eslint-disable-next-line no-empty
      let fileTofolder = {
        id: getNowMilliSecond(),
        fileType: "folder",
        fileName: product.foldername,
        filePath: "",
        documentsType: product.id,
        uploadTime: getcurDate(),
        dirname: product.name,
        mtype: 6,
        pname: product.pname,
        size: 0,
        fid: getRandomId()
      }
      list.push(fileTofolder)
      fs.writeFile(getAppLocalPath()+'dbson/AccessToMaterials.dbson', JSON.stringify(list), function(err) {
        if (err) {
          fileTofolder.status=0
          resolve(fileTofolder)
          return
        }
        fileTofolder.status=1
        resolve(fileTofolder)
      })
    })
  })
}
export function makeFolder2(product) {
  return new Promise((resolve, reject) => {
    console.log("f--",product)
    //新增文件表
    fs.readFile(getAppLocalPath()+'dbson/SysFileLists.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      // eslint-disable-next-line no-empty
      let fileTofolder = {
        id: getNowMilliSecond(),
        fileType: "folder",
        fileName: product.foldername,
        filePath: "",
        documentsType: product.id,
        uploadTime: getcurDate(),
        dirname: product.name,
        mtype: 6,
        pname: product.pname,
        size: 0,
        fid: getRandomId()
      }

      const morelist=list.data.filter(reu=>{
        return reu.f_directory_name_===product.foldername
      })

      if(morelist!=undefined&&morelist.length>0){
        fileTofolder.status=2
        resolve(fileTofolder)
        return
      }

      let folder={
        parent_id_: "1652855656765575170",
        del_flag_: "1",
        create_dep_id_: "1",
        f_patrol_object_name_: "市行政审批服务局",
        create_by_: "2023",
        id_: getNowMilliSecond()+"",
        serial_num_: 1,
        tenant_id_: "1",
        f_directory_name_: product.foldername,
        create_time_: getcurDate(),
        f_serial_number_: 0,
        f_term_id_: "1633009491647741953",
        update_time_:getcurDate(),
        f_patrol_object_id_: "1652855656765575170",
        f_directory_type: "loanMaterial"
      }
      list.data.push(folder)
      fs.writeFile(getAppLocalPath()+'dbson/SysFileLists.dbson', JSON.stringify(list), function(err) {
        if (err) {
          fileTofolder.status=0
          resolve(fileTofolder)
          return
        }
        fileTofolder.status=1
        resolve(fileTofolder)
      })
    })
  })
}
//删除文件夹
export function delFolder2(product) {
  return new Promise((resolve, reject) => {
    console.log("f--",product)
    //新增文件表
    fs.readFile(getAppLocalPath()+'dbson/SysFileLists.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)

      const fileTofolder={}

      const morelist=list.data.filter(reu=>{
        return reu.create_by_==="2023"&&reu.f_directory_name_===product.name
      })

      if(morelist.length===0){
        fileTofolder.status=2
        resolve(fileTofolder)
        return
      }

      const lastlist=list.data.filter(reu=>{
        return reu.f_directory_name_!=product.name
      })

      list.data=lastlist

      fs.writeFile(getAppLocalPath()+'dbson/SysFileLists.dbson', JSON.stringify(list), function(err) {
        if (err) {
          fileTofolder.status=0
          resolve(fileTofolder)
          return
        }
        fileTofolder.status=1
        resolve(fileTofolder)
      })
    })
  })
}
export const  setUnitName=(unitName)=>{
  const user=JSON.parse(fs.readFileSync(getAppLocalPath()+"dbson/User.dbson","utf-8"))
  user.unitName=unitName
  console.log("nmnm--",user.unitName)
  fs.writeFileSync(getAppLocalPath()+"dbson/User.dbson",JSON.stringify(user))
}
//移动文件
export function moveFile2(product,folder) {
  return new Promise((resolve, reject) => {
    console.log("f--",product)
    //新增文件表
    const filders=JSON.parse(fs.readFileSync(getAppLocalPath()+'dbson/SysFileLists.dbson', 'utf-8')).data
    let fold=filders.filter(filt=>{
      return filt.id_===folder[0]
    })
    fs.readFile(getAppLocalPath()+'dbson/AccessToMaterials.dbson', 'utf-8', function(err, dataStr) {
      const list = JSON.parse(dataStr)
      console.log("fff--",fold)
      //被移动到文件夹判重
      const listcheck=list.filter(it=>{
        return (it.documentsType===folder[0]&&it.fileName===product.fileName)
      })
      if(listcheck.length>0){
        resolve(2)
        return
      }
      list.forEach(it=>{
        if(it.id===product.id){
          it.documentsType=fold[0].id_
          it.dirname=fold[0].f_directory_name_
        }
      })
      fs.writeFile(getAppLocalPath()+'dbson/AccessToMaterials.dbson', JSON.stringify(list), function(err) {
        if (err) {
          resolve(0)
          return
        }
        resolve(1)
      })
    })
  })
}
export const  getUnitName=()=>{
  const user=JSON.parse(fs.readFileSync(getAppLocalPath()+"dbson/User.dbson","utf-8"))
  return  user.unitName
}

export const testfile=()=>{
  //demo.js
  var fs = require('fs');  //引入fs模块，对文件进行操作
  var archiver = require('archiver'); // archiver可用于普通的打包压缩
  var filePath = 'test/'; //获取文件路径
  var dirList = fs.readdirSync(filePath); //获取文件列表
  console.log("dl---",dirList)
  var zipPath = 'zip_package/test_folder.zip';  //压缩包生成路径
// register format for archiver
  // archiver.registerFormat('zip-encrypted', require("archiver-zip-encrypted"));
//创建最终打包文件的输出流
  var output = fs.createWriteStream(zipPath);
//生成archiver对象，打包类型为zip
// create archive and specify method of encryption and password
  var archive = archiver.create('zip-encrypted',
    {
      zlib: {
        level: 8,//压缩等级
      },
      encryptionMethod: 'aes256',//加密方法
      password: '123',//解压密码
    }
  );
//对文件压缩,
// archive.file('test_folder/test.txt', { name: 'text.txt' });//第一个源文件,第二个生成到压缩包的文件
//对文件夹进行压缩
  var stream = fs.createReadStream("test" + "/123.doc");// 读取当前目录下的hello.txt
  archive.append(stream, {name: '123.doc'});
  //archive.directory(filePath, false);
  archive.pipe(output); //将打包对象与输出流关联
//监听所有archive数据都写完
  output.on('close', function() {
    console.log('压缩完成', archive.pointer() / 1024 / 1024 + 'M');
  });
  archive.on('error', function(err) {
    console.log("压缩失败!");
    throw err;
  });
//打包
  archive.finalize();
}
export const testfile3=()=>{
  // require modules
  const fs = require('fs');
  const archiver = require('archiver');

// create a file to stream archive data to.
  const output = fs.createWriteStream(__dirname + '/example.zip');
  const archive = archiver('zip', {
    zlib: { level: 9 } // Sets the compression level.
  });

// listen for all archive data to be written
// 'close' event is fired only when a file descriptor is involved
  output.on('close', function() {
    console.log(archive.pointer() + ' total bytes');
    console.log('archiver has been finalized and the output file descriptor has closed.');
  });

// This event is fired when the data source is drained no matter what was the data source.
// It is not part of this library but rather from the NodeJS Stream API.
// @see: https://nodejs.org/api/stream.html#stream_event_end
  output.on('end', function() {
    console.log('Data has been drained');
  });

// good practice to catch warnings (ie stat failures and other non-blocking errors)
  archive.on('warning', function(err) {
    if (err.code === 'ENOENT') {
      // log warning
    } else {
      // throw error
      throw err;
    }
  });

// good practice to catch this error explicitly
  archive.on('error', function(err) {
    throw err;
  });

// pipe archive data to the file
  archive.pipe(output);

// append a file from stream
  const file1 = __dirname + '/base.db';
  archive.append(fs.createReadStream(file1), { name: 'file1.db' });

// append a file from string
  //  archive.append('string cheese!', { name: 'file2.txt' });

// // append a file from buffer
//    const buffer3 = Buffer.from('buff it!');
//    archive.append(buffer3, { name: 'file3.txt' });
//
// // append a file
//    archive.file('file1.txt', { name: 'file4.txt' });
//
// // append files from a sub-directory and naming it `new-subdir` within the archive
//    archive.directory('subdir/', 'new-subdir');
//
// // append files from a sub-directory, putting its contents at the root of archive
//    archive.directory('subdir/', false);
//
// // append files from a glob pattern
//    archive.glob('file*.txt', {cwd:__dirname});

// finalize the archive (ie we are done appending files but streams have to finish yet)
// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
  archive.finalize();
}
export  const ttst=()=>{
  const s=fs.readFileSync("chrtc/lanjian_supervision_plan","utf-8")
  decodeFile(s)
}
